<template lang="pug">

.tab-wrapper
  .tabBar-wrapper
    cube-tab-bar(v-model="selectedLabel"
                  :data="tabs"
                  show-slider
                  ref="tabBar")
  .slide-wrapper
    cube-slide(:data="tabs"
                :loop="false"
                :auto-play="false"
                :show-dots="false"
                :useTransition="false"
                :initial-index="currentTabIndex"
                :options="options"
                @change="changePage"
                @scroll="scroll"
                ref="slide")
      cube-slide-item(v-for="(tab, index) in tabs" :key="index")
        component(:is="tab.component" :tabIndex="index" ref="component")

</template>

<script>
import {mapState} from 'vuex'

export default {
  name: 'tab',

  props: {

    seller: {
      type: Object,
      default() {
        return {}
      }
    },

    tabs: {
      type: Array,
      default() {
        return []
      }
    }

  },

  data () {
    return {
      options: {
        listenScroll: true,
        probeType: 3,
        directionLockThreshold: 0
      }
    }
  },

  computed: {
    // 全局变量
    ...mapState({
      // 当前tab页签码
      currentTabIndex: 'currentTabIndex'
    }),

    selectedLabel: {
      get() {
        return this.tabs[this.currentTabIndex].label
      },
      set(newVal) {
        let currentIndex = this.tabs.findIndex((value)=>{
          return value.label === newVal
        })
        this.$store.dispatch('setCurrentTabIndex', currentIndex)
      }
    }
  },

  methods: {
    changePage(current) {
      console.log('当前轮播图序号为:' + current)
      this.$store.dispatch('setCurrentTabIndex', current)
      const component = this.$refs.component[current]
      component.fetch && component.fetch()
    },

    scroll ({x, y}) {
      console.log(x, y)
      const tabbarWidth = this.$refs.tabBar.$el.clientWidth
      const slideWidth = this.$refs.slide.slide.scrollerWidth
      const transform = -x / slideWidth * tabbarWidth
      // 手动设置tab头部的transform值
      this.$refs.tabBar.setSliderTransform(transform)
    }
  },

  mounted() {
    this.changePage(this.currentTabIndex)
  }

}
</script>

<style lang="stylus" scoped>
@import "../../static/common/stylus/variable";

.tab-wrapper
  display:flex
  width:100%
  height:100%
  flex-direction: column
  .tabBar-wrapper
    flex:0 0 36px
    >>> .cube-tab
      padding:10px 0
    >>> .cube-tab_active
      color: $color-red
    >>> .cube-tab-bar-slider
      background-color: $color-red
  .slide-wrapper
    flex:1
    .cube-slide-item
      position:relative

</style>
 
